﻿using System;
using System.Text;
using System.Security.Cryptography;

namespace ShenLan.Common
{
    public class Encrypt
    {
        /// <summary>
        /// 加密密码
        /// </summary>
        /// <param name="str">待加密的字符</param>
        /// <returns>加密后的字符</returns>
        public static string EnctyptPassword(string str)
        {
            var base64 = StrToBase64(str);
            var md5pass = StrToMd5_32String(base64);
            return md5pass;
        }

        /// <summary>
        /// 将字符进行base64编码
        /// </summary>
        /// <param name="str">要进行base64编码的字符</param>
        /// <returns>base64编码后的字符</returns>
        private static string StrToBase64(string str)
        {
            var base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(str));
            return base64;
        }

        /// <summary>
        /// 对字符进行md5 32位加密,加密后为大写
        /// </summary>
        /// <param name="str">要加密的字符</param>
        /// <returns>md5加密后的32位字符串</returns>
        private static string StrToMd5_32String(string str)
        {
            MD5 md = new MD5CryptoServiceProvider();
            byte[] b = md.ComputeHash(Encoding.UTF8.GetBytes(str));
            var md5str = BitConverter.ToString(b).Replace("-", "");
            return md5str;
        }

        /// <summary>
        /// 方法1:对字符进行md5 16位加密 加密后为大写
        /// </summary>
        /// <param name="str">要加密的字符</param>
        /// <returns>md5加密后的32位字符串</returns>
        private static string StrToMd5_16String(string str)
        {
            MD5 md = new MD5CryptoServiceProvider();
            byte[] b = md.ComputeHash(Encoding.UTF8.GetBytes(str));
            var md5str = BitConverter.ToString(b).Replace("-", "").Substring(8, 16);
            return md5str;
        }

        /// <summary>
        /// 方法2:对字符进行md5 16位加密 加密后为大写
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string StrToMd5_16String1(string str)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string md5Str = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(str)), 4, 8);
            md5Str = md5Str.Replace("-", "");
            return md5Str;
        }
    }
}